/*
@(#)TraceInterceptor   2024-01-23
 
Copyright (c) 2011-2024 杭州湖畔网络技术有限公司 
保留所有权利 
本软件为杭州湖畔网络技术有限公司所有及包含机密信息，须遵守其相关许可证条款进行使用。
Copyright (c) 2011-2024 HUPUN Network Technology CO.,LTD.
All rights reserved.
This software is the confidential and proprietary information of HUPUN
Network Technology CO.,LTD("Confidential Information").  You shall not
disclose such Confidential Information and shall use it only in
accordance with the terms of the license agreement you entered into with HUPUN.
Website：http://www.hupun.com
*/
package org.obp.auth.filter;

import cn.dev33.satoken.stp.StpUtil;
import org.apache.commons.lang3.StringUtils;
import org.obp.core.context.ObpContext;
import org.obp.core.result.ApiResult;
import org.obp.core.session.TraceSession;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author: Jackey 2024/1/23
 */
@Order(1)
@Component
public class TraceInterceptor implements HandlerInterceptor {

    @Value("${spring.profiles.active}")
    private String profile;
    @Value("${sa-token.token-name:auth-token}")
    private String tokenHeader;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String traceID = initTraceID();
        MDC.put(ApiResult.TRACE_ID, traceID);

        TraceSession traceSession = buildTraceSession(request, traceID);
        ObpContext.initSession(traceSession);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        MDC.remove(ApiResult.TRACE_ID);
        ObpContext.clearSession();
    }

    private String initTraceID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    private TraceSession buildTraceSession(HttpServletRequest request, String traceID) {
        TraceSession traceSession = new TraceSession();
        traceSession.setProfile(profile);
        traceSession.setTraceId(traceID);
        String token = request.getHeader(tokenHeader);
        if (StringUtils.isNotEmpty(token)) {
            Object loginID = StpUtil.getLoginIdByToken(token);
            if (loginID != null) traceSession.setUserId(String.valueOf(loginID));
        }
        return traceSession;
    }

}